package com.wang.controller;

import com.wang.entity.Books;
import com.wang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")//接口有多个实现类，确定唯一一个要操作的实现类
    private BookService bookService;
    @RequestMapping("/allBook")
    public String list(Model model)
    {
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";

    }
    //添加书籍的页面
    @RequestMapping("/toAddBook")
    public String toAddPaper()
    {
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books)
    {
        System.out.println("addBook>="+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }
    @RequestMapping("/updateBook/{bookID}")
    //修改书籍的页面
    public String toUpdateBook(@PathVariable("bookID") int id,Model model)
    {
        Books books = bookService.queryBookById(id);
        model.addAttribute("Qbooks",books);
        return "udataBook";
    }
    //修改书籍
    @RequestMapping("/changeBook")
    public String toChangeBook(Books books)
    {
        System.out.println("updateBook>="+books);
        int i = bookService.updateBook(books);
        if(i>0)
        {
            System.out.println("添加成功");
        }
        else
        {
            System.out.println("添加失败");
        }
        bookService.queryAllBook();
        return "redirect:/book/allBook";

    }

    //删除书籍
    @RequestMapping("/deleteBook/{a}")
    public String deleteBook(@PathVariable("a") int id)
    {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    //根据书籍名称查询书籍
    @RequestMapping("/queryBookByName")
    public String queryBookByName(String queryBookByName,Model model)
    {
        List<Books> books = bookService.queryBookByName(queryBookByName);
        System.err.println(books);


        if(books==null)
        {
            model.addAttribute("error","查询书籍不存在");
        }
        model.addAttribute("list",books);
        return "allBook";
    }


}
